from django.db.models import Q
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .ser import *
from django.core.paginator import Paginator
from .filters import UserFilter
from django_filters.rest_framework import DjangoFilterBackend
# from .models import *


# Create your views here.
class UserView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username,password=password).first()
        if user:
            return Response({'code':200,'message':'登录成功','uid':user.id})
        else:
            return Response({'message': '登录失败', 'code': 400})

    def get(self,request):
        user_list = User.objects.all()
        user_ser = UserSerializers(user_list,many=True)
        return Response(user_ser.data)



class ChaView(APIView):
    def post(self,request):
        gt = request.data.get('gt')
        lt = request.data.get('lt')
        page = request.data.get('p')
        print(page)
        if all([gt,lt]):
            user_lsit = User.objects.filter(payment__gte=gt).filter(payment__lte = lt)
        elif gt:
            user_lsit = User.objects.filter(payment__gte=gt)
        elif lt:

            user_lsit = User.objects.filter(payment__lte = lt)
        else:
            user_lsit = User.objects.all()
        pageinfo = Paginator(user_lsit, 2)
        book_info = pageinfo.page(int(page))
        book_list = [i for i in pageinfo.page_range]
        ser_foods = UserSerializers(book_info, many=True)
        res_data = {
            'all_page': pageinfo.num_pages,
            'data': ser_foods.data,
            'page': book_info.number,
            'page_list': book_list
        }
        return Response(status=200, data=res_data)

# 调用过滤器
class UserViewSet(ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializers
        filter_backends = (DjangoFilterBackend,)
        filter_class = UserFilter





